package com.tkjt.pms.modules.budget.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tkjt.pms.common.entity.TkDataConfig;
import com.tkjt.pms.modules.budget.common.DataTypeVo;
import com.tkjt.pms.modules.common.service.TkDataConfigService;

@RestController
@RequestMapping("/api/pms/budget")
public class budgetController {

	@Autowired
	private TkDataConfigService tkDataConfigService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;

	@RequestMapping(value = "dataTypeCtrl")
	public Result<?> dataTypeCtrl(@RequestBody TkDataConfig tkDataConfig) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (loginUser == null) {
			return Result.error("用户非法！");
		}
		if (StringUtils.isEmpty(tkDataConfig.getUserName())) {
			return Result.error("参数缺失！");
		}

		try {
			tkDataConfigService.dataTypeCtrl(loginUser, tkDataConfig);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("获取数据异常");
		}
		return Result.ok();
	}

	@RequestMapping(value = "dataTypeQuery")
	public Result<?> dataTypeQuery(@RequestBody DataTypeVo dataTypeVo) {
		String userName = dataTypeVo.getUserName();
		if (StringUtils.isEmpty(userName)) {
			LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			userName = loginUser.getUsername();
		}
		List<String> userRoleCodes = sysUserRoleService.getUserRoles(userName);
		if(CollectionUtils.isEmpty(userRoleCodes)) {
			return Result.ok(new ArrayList<DataTypeVo>());
		}
		if (!(userRoleCodes.contains("ykkpiowner") || userRoleCodes.contains("ykgm") || userRoleCodes.contains("ykaudit")) && (userRoleCodes.contains("ykgheader") || userRoleCodes.contains("ykcheader"))) {
			return Result.ok(new ArrayList<DataTypeVo>());
		}
		List<DataTypeVo> dataTypes = tkDataConfigService.listDataTypes(userName);
		if (CollectionUtils.isEmpty(dataTypes)) {
			return Result.ok(new ArrayList<DataTypeVo>());
		} else {
			return Result.ok(dataTypes);
		}
	}

}
